//
//  XMPictureShowVC.m
//  BigJoy
//
//  Created by 罗晓明 on 2017/11/2.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "XMPictureShowVC.h"
#import "XMPicCell.h"
#import "PhotoBrowser.h"
#import "XMPictrueDownloadActionView.h"
//#import "SDWebImageDownloader.h"
#import "SGDialog.h"
#import <SDWebImage/SDWebImageDownloader.h>
#import "Masonry/Masonry.h"
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)
#define SG_BOTTOM_SPACE     (SG_IS_IPhoneX_All ? 34.0 : 0.0)
#define SG_STATUS_HEIGHT     (CGRectGetMaxY([UIApplication sharedApplication].statusBarFrame))
@interface XMPictureShowVC ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong) UICollectionView * collectionView;
@property(nonatomic,strong)NSMutableArray * urlArray;
@property(nonatomic,assign) NSInteger index;
@property(nonatomic,strong)PhotoBrowser * browser;
@property(nonatomic,strong)UILabel * titleLable;
@end

@implementation XMPictureShowVC

-(PhotoBrowser *)browser {
    if (_browser == nil) {
        _browser = [[PhotoBrowser alloc]init];
    }
    return _browser;
}

-(instancetype)initWithImageArray:(NSArray *)urlArray index:(NSInteger )index{
    self = [super init];
    if (self) {
        _index = index;
        _urlArray = urlArray;
        self.modalPresentationStyle = UIModalPresentationCustom;
        self.transitioningDelegate = self.browser;
    }
    return self;
}

-(UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = self.view.bounds.size;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing= 0;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[XMPicCell class] forCellWithReuseIdentifier:@"Cell"];
    }
    return _collectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.collectionView];
    UILabel * titleLable = [UILabel new];
    [self.view addSubview:titleLable];
    self.titleLable = titleLable;
    [titleLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(15 + SG_STATUS_HEIGHT);
    }];
    titleLable.textColor = [UIColor whiteColor];
    self.collectionView.contentOffset = CGPointMake(self.index * SCREEN_WIDTH, 0);
    [self refreshTitleLabel];
    UIButton * saveButton = [UIButton new];
    [self.view addSubview:saveButton];
    [saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)){
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuide).offset(-15);
        }else {
            make.bottom.equalTo(self.view).offset(-15);
        }
        make.right.equalTo(self.view).offset(-15);
        make.width.equalTo(@80);
        make.height.equalTo(@40);
    }];
//    saveButton.layer.borderWidth = 1;
//    saveButton.layer.borderColor = [UIColor whiteColor].CGColor;
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [saveButton setTitle:@"保存" forState:UIControlStateNormal];
    [saveButton setImage:[UIImage imageNamed:@"save"] forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(savePoto) forControlEvents:UIControlEventTouchUpInside];
    saveButton.hidden = NO;
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor blackColor];
    [self addDeleteBtn];
}

-(void)refreshTitleLabel {
    self.titleLable.text = [NSString stringWithFormat:@"%ld/%ld",self.index + 1,self.urlArray.count];
}

-(void)addDeleteBtn {
    // deleteButton
    UIButton * DeleBtn = [UIButton new];
    [self.view addSubview:DeleBtn];
    [DeleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.titleLable);
        make.right.equalTo(self.view).offset(-15);
        make.width.equalTo(@30);
        make.height.equalTo(@30);
    }];
    [DeleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [DeleBtn setImage:[UIImage imageNamed:@"baiselaji"] forState:UIControlStateNormal];
    [DeleBtn addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
    DeleBtn.hidden = !self.showDelete;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    XMPicCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    if (self.suolvUrlArray) {
        cell.suolvUrl = self.suolvUrlArray[indexPath.row];
    }
    if (self.urlArray) {
        cell.imgUrl = self.urlArray[indexPath.row];
    }
     __weak typeof(self)weakSelf = self;
    [cell setTapBlock:^{
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [cell setLongPressBlock:^{
        XMPictrueDownloadActionView * v = [XMPictrueDownloadActionView fastLogin];
        v.frame = self.view.bounds;
        [v setOnSave:^{
//            HDSDWebImageManager
//            NSString * u = [NSString stringWithFormat:@"%@",self.urlArray[indexPath.row]];
//            [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:u] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//                
//            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
//                if (image) {
//                    UIImageWriteToSavedPhotosAlbum(image, self, @selector(onSaveImage:error:contextInfo:), nil);
//                }
//            }];
        }];
        [self.view addSubview:v];
    }];
    return cell;
}

-(void)onSaveImage:(UIImage *)image error:(NSError *)error contextInfo:(id)contextInfo {
//    NSLog(@"图片保存成功");
//    if (self.onSave) {
//        self.onSave();
//    }
    if (error == nil) {
        [SGDialog showWeakStr:@"图片保存成功" withImg:@""];
    } else {
        [SGDialog showWeakStr:@"图片保存失败" withImg:@""];
    }
//    [SGDialog showErrorMessage:@"图片保存成功"];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
     NSIndexPath * indexpath = self.collectionView.indexPathsForVisibleItems.firstObject;
    self.index = indexpath.row;
    [self refreshTitleLabel];
}


// 删除照片
-(void)delete {
//    [DilogBoxVC showInVC:self Content:Localized(@"您确定删除吗") leftTitle:Localized(@"取消") rightTiltle:Localized(@"确定") RightBlock:^{
//        NSIndexPath * indexpath = self.collectionView.indexPathsForVisibleItems.firstObject;
//        NSMutableArray * array = [self.urlArray mutableCopy];
//        [array removeObjectAtIndex:indexpath.row];
//        [SGDialog showLoad];
//        NSLog(@"%lf",self.collectionView.contentOffset.x);
//        [self updateKey:@"imgs" withValue:[AppHelper arrayToStr:array] compelete:^{
//            [self.urlArray removeObjectAtIndex:indexpath.row];
//            [self.collectionView reloadData];
//            [self.collectionView layoutSubviews];
//            NSLog(@"%lf",self.collectionView.contentOffset.x);
//            self.index = (NSInteger)(self.collectionView.contentOffset.x / SG_SCREEN_WIDTH);
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                NSLog(@"%lf",self.collectionView.contentOffset.x);
//            });
//            [self refreshTitleLabel];
//            if (self.sourceHasChangeBlock) {
//                self.sourceHasChangeBlock();
//            }
//            if (self.urlArray.count == 0) {
//                [self dismissViewControllerAnimated:YES completion:nil];
//            }
//        }];
//    }];
}

-(void)updateKey:(NSString *)key withValue:(id)value compelete:(void(^)(void))compelete{
//    NSDictionary * dic = @{
//                           key : value
//                           };
//    RacParam * par = [RacParam new];
//    par.body = dic.mj_JSONString;
//    [[[APIManager shareInstance].ChangeInfo execute:par] subscribeNext:^(RESCODE) {
//        if (response.success == 0) {
//            [SGDialog dismiss];
//            if (compelete) {
//                compelete();
//            }
//        }
//    }];
}

// 保存图片
-(void)savePoto {
//    [DilogBoxVC showInVC:self Content:Localized(@"是否要保存当前图片") leftTitle:Localized(@"取消") rightTiltle:Localized(@"保存") RightBlock:^{
//        NSIndexPath * indexpath = self.collectionView.indexPathsForVisibleItems.firstObject;
//        XMPicCell * cell = (XMPicCell *)[self.collectionView cellForItemAtIndexPath:indexpath];
//        if (cell.imageView.image) {
//
//        } else {
//            [SGDialog showWeakStr:@"保存出错"];
//        }
//        UIImageWriteToSavedPhotosAlbum(cell.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//    }];
}
// 保存是否成功的监听
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
//    if (error == nil ){
//        [SGDialog showWeakStr:@"保存成功"];
//    } else {
//        [SGDialog showWeakStr:@"保存失败"];
//    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.urlArray.count;
}

-(void)dealloc {
    NSLog(@"%@ is dealloced",NSStringFromClass([self class]));
}
@end
